<?php 
header('Content-type: application/x-javascript'); 

include_once('auth.php');

echo "var pData = {";

	
function base64url_decode($base64url) {
	$base64 = strtr($base64url, '-_', '+/');
	$plainText = base64_decode($base64);
	return ($plainText);
}
function base64url_encode($plainText) {
	$base64 = base64_encode($plainText);
	$base64url = strtr($base64, '+/', '-_');
	return ($base64url);   
}
function truncat($source, $length) {
	if (strlen($source) > $length)
		return trim(substr($source, 0, $length)).'...';
	else return $source;
}
function rp($p) {
    $p=explode('/', $p);
    $o=array();
    for ($i=0; $i<sizeof($p); $i++) {
        if (''==$p[$i] || '.'==$p[$i]) continue;
        if ('..'==$p[$i] && $i>0 && '..'!=$o[sizeof($o)-1]) {
            array_pop($o);
            continue;
        }
        array_push($o, $p[$i]);
    }
    return implode('/', $o);
}


if (isset($_GET['path'])) {
	include_once('libs/itunes_xml_parser_php5.php');
	
	$rawpath = $_GET['path'];
	$decodedpath = base64url_decode($rawpath);

	$playlist = iTunesXmlParser($decodedpath);

	$thisdir = $_SERVER["SCRIPT_NAME"];
	
	$i=0;
	foreach ($playlist as $entry) {
		$entry['Location'] = str_replace($ITUNES_PATH_REPLACESTRING,$MP3_LIBRARY_LOCATION,$entry['Location']);
		
		echo "	$i:{\n";
		echo "		name	:		'", addslashes($entry['Name']), 	"',\n";
		echo "		artist	:		'", addslashes($entry['Artist']), 	"',\n";
		echo "		album	:		'", (isset($entry['Album'])?addslashes($entry['Album']):""), 	"',\n";
		echo "		time	:		", round($entry['Total Time']/1000), 	",\n";
		echo "		rating	:		", (isset($entry['Rating'])?$entry['Rating']:"0"), 	",\n";
		echo "		realpath:		'", addslashes($entry['Location']), "',\n";
		echo "		encodedpath:		'", base64url_encode($entry['Location']), "',\n";
		echo "	},\n";
		$i++;
	}
	
	echo "	length:$i\n};\n";
//	echo "delete pData[$i];";
	echo "Musiker.modHardPlaylists.playlistContents['$rawpath'] = pData;\n";
	echo "Musiker.modHardPlaylists.load('$rawpath', true);\n";

} else echo "alert('No playlist file was provided')";
?>

